package com.dlc.shop.platform.controller;

import com.dlc.shop.allinpay.service.AllinpayCompanyService;
import com.dlc.shop.bean.enums.AuditStatus;
import com.dlc.shop.bean.model.ShopCompany;
import com.dlc.shop.bean.model.ShopDetail;
import com.dlc.shop.bean.vo.ShopCompanyVO;
import com.dlc.shop.common.Ocr.RecognizeBankCardOcr;
import com.dlc.shop.common.Ocr.RecognizeBusinessLicenseOcr;
import com.dlc.shop.common.Ocr.RecognizeIdcardOcr;
import com.dlc.shop.common.allinpay.constant.AllinpayConstant;
import com.dlc.shop.common.allinpay.constant.IdCardCollectProcessStatus;
import com.dlc.shop.common.allinpay.member.resp.CompanyInfo;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.common.util.ExceptionUtils;
import com.dlc.shop.jky.common.foreign.service.ForeignShopService;
import com.dlc.shop.service.ShopCompanyService;
import com.dlc.shop.service.ShopDetailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Author lth
 * @Date 2021/8/4 14:44
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/platform/shopCompany")
@Tag(name = "商家工商信息")
public class ShopCompanyController {

    private final ShopCompanyService shopCompanyService;
    private final AllinpayCompanyService allinpayCompanyService;
    private final ShopDetailService shopDetailService;
    private final ForeignShopService foreignService;
    @GetMapping
    @Operation(summary = "根据店铺id获取店铺工商信息", description = "根据店铺id获取店铺工商信息")
    @Parameter(name = "shopId", description = "店铺id")
    @PreAuthorize("@pms.hasPermission('platform:shopCompany:info')")
    public ServerResponseEntity<ShopCompanyVO> getShopCompanyByShopId(@RequestParam("shopId") Long shopId, @RequestParam(value = "status", required = false, defaultValue = "1") Integer status) {
        if (allinpayCompanyService.getIsAllinpay()) {
            // 影印件还没通过审核
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
            if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                status = AuditStatus.WAITAUDIT.value();
            }
        }
        ShopCompanyVO shopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, status);
        return ServerResponseEntity.success(shopCompany);
    }

    @PutMapping
    @Operation(summary = "更新店铺工商信息", description = "更新店铺工商信息")
    @PreAuthorize("@pms.hasPermission('platform:shopCompany:update')")
    public ServerResponseEntity<Void> editShopCompany(@RequestBody @Valid ShopCompany shopCompany) {
        boolean isAllinpay = allinpayCompanyService.getIsAllinpay();
        shopCompany.setStatus(isAllinpay ? AuditStatus.WAITAUDIT.value() : AuditStatus.SUCCESSAUDIT.value());
        if (isAllinpay) {
            shopCompanyService.platformUpdateShopCompany(shopCompany, shopCompany.getShopId());
        } else {
            shopCompanyService.updateByShopId(shopCompany);
        }
        //修改平台端工商信息 发往国外
        ////foreignService.editShopCompany(shopCompany);
        return ServerResponseEntity.success();
    }

    @GetMapping("/checkCreditCode")
    @Operation(summary = "检查统一信用码是否已存在", description = "检查统一信用码是否已存在")
    @Parameter(name = "creditCode", description = "信用码")
    @PreAuthorize("@pms.hasPermission('platform:shopCompany:check')")
    public ServerResponseEntity<Boolean> checkCreditCode(@RequestParam(value = "creditCode") String creditCode, @RequestParam("shopId") Long shopId) {
        return ServerResponseEntity.success(shopCompanyService.checkCreditCode(creditCode, shopId));
    }

    @PutMapping("/updateIdCardStatus")
    @Operation(summary = "更新影印件状态", description = "通联独有")
    @PreAuthorize("@pms.hasPermission('platform:shopCompany:update')")
    public ServerResponseEntity<Integer> updateIdCardStatus(@RequestParam("shopId") Long shopId) {
        if (!allinpayCompanyService.getIsAllinpay()) {
            return ServerResponseEntity.success();
        }
        if (Objects.isNull(shopId)) {
            throw new YamiShopBindException("店铺id不能为空");
        }
        ShopCompanyVO shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
        if (Objects.isNull(shopCompanyVO)) {
            shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.SUCCESSAUDIT.value());
        }
        ShopDetail shopDetailVO = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
            // 更新下更新时间
            shopCompanyService.updateById(BeanUtil.map(shopCompanyVO, ShopCompany.class));
            // 已经审核通过不用更新
            return ServerResponseEntity.success(shopDetailVO.getIdCardCollectProcessStatus());
        }
        // 可能回调有问题导致这里没刷新，所以多给一个接口
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(AllinpayConstant.SHOP + shopId);
        Integer status = allinpayCompanyService.getIdCardStatus(companyInfo.getOcrRegnumComparisonResult(), companyInfo.getOcrIdcardComparisonResult());
        if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), status)) {
            // 更新下更新时间
            shopCompanyService.updateById(BeanUtil.map(shopCompanyVO, ShopCompany.class));
            // 状态一致不用更新
            return ServerResponseEntity.success(status);
        }
        shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, status);
        shopDetailService.removeShopDetailCacheByShopId(shopId);
        return ServerResponseEntity.success(status);
    }

    @PutMapping("/uploadIdCard")
    @Operation(summary = "重新上传影印件", description = "通联独有")
    public ServerResponseEntity<String> uploadIdCard(@RequestBody ShopCompany shopCompanyDTO) {
        if (!allinpayCompanyService.getIsAllinpay()) {
            return ServerResponseEntity.success("非通联环境");
        }
        Long shopId = shopCompanyDTO.getShopId();
        if (Objects.isNull(shopId)) {
            throw new YamiShopBindException("店铺id不能为空");
        }
        ShopDetail shopDetailVO = shopDetailService.getShopDetailByShopId(shopId);
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(AllinpayConstant.SHOP + shopId);
        Integer status = allinpayCompanyService.getIdCardStatus(companyInfo.getOcrRegnumComparisonResult(), companyInfo.getOcrIdcardComparisonResult());
        String result = shopCompanyService.uploadIdCard(shopCompanyDTO, shopDetailVO, status);
        shopDetailService.removeShopDetailCacheByShopId(shopId);
        if (!Objects.equals(result, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS) || Objects.equals(result, AllinpayConstant.ID_CARD_UPDATE_SUCCESS)) {
            return ServerResponseEntity.showFailMsg(result);
        }
        return ServerResponseEntity.success(result);
    }

    /**
     * ocr 识别
     */
    @GetMapping("/ocr")
    @Operation(summary = "ocr识别", description = "ocr识别，URL 就是文件地址，type ：1 身份证正反面，2 营业执照，3 银行卡")
    public ServerResponseEntity<String> translate( String url, Integer type) {
        try {
            switch (type) {
                case 1:
                    //身份证信息返回
                    return ServerResponseEntity.success(RecognizeIdcardOcr.recognizeIdcardUntils(url));

                case 2:
                    // 营业执照
                    return ServerResponseEntity.success(RecognizeBusinessLicenseOcr.recognizeBusinessLicenseOcrUntils(url));

                case 3:
                    // 银行卡
                    return ServerResponseEntity.success( RecognizeBankCardOcr.recognizeBankCardOcr(url));

            }
        } catch (Exception e) {
            log.error("图片ocr 识别失败： "+ ExceptionUtils.getRunException(e));
        }
        return ServerResponseEntity.success();

    }
}
